package com.elasticsearch.demo.service.user;

import com.elasticsearch.demo.model.entity.Role;
import com.elasticsearch.demo.model.entity.User;
import com.elasticsearch.demo.repository.RoleRepository;
import com.elasticsearch.demo.repository.UserRepository;
import com.elasticsearch.demo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RoleRepository roleRepository;

    @Override
    public User findUserByName(String userName) {

        User ret = null;

        User user = userRepository.findByName(userName);

        if(user != null){

            List<Role> roles = roleRepository.findByUserId(user.getId());
            if (roles == null || roles.isEmpty()) {
                throw new DisabledException("权限非法");
            }

            List<GrantedAuthority> authorities = new ArrayList<>();
            roles.forEach(role -> authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName())));
            user.setAuthorityList(authorities);

            ret = user;

        }

        return ret;
    }
}
